<?php
namespace app\client\controller;
use app\common\lib\Redis;
use think\swoole\facade\Task;

class User extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function bindMobile() {
        $params = request()->post();
        if(empty($params)){
            return errorResult('a');
        }
        
        try {
            $model = model('User');
            
            $sessionKey = $model->where(['user_id' => $this->userid])->value('session_key');
            $appId = config('config.wx.appid');
            $pc = new \app\client\lib\WXBizDataCrypt\WXBizDataCrypt($appId, $sessionKey);
            $errCode = $pc->decryptData($params['encryptedData'], $params['iv'], $userInfo);
            $userInfo = json_decode($userInfo, true);
            if($errCode || empty($userInfo) || empty($userInfo['phoneNumber'])) {
                return errorResult();
            }
            
            $model->modify(['user_id' => $this->userid], ['mobile' => $userInfo['phoneNumber']]);
            return successResult();
        } catch (\Exception $e) {
            return errorResult('操作失败');
        }
        
        
    }
    
    public function userInfo() {
        $params = request()->post();
        if(empty($params)){
            return errorResult('a');
        }
        
        $appId = config('config.wx.appid');
        $userModel = model('User');
        $userId = $this->userid;
        
        $field = 'session_key, unionid, nickname, avatar, sex, user_type, merchant_begin, merchant_annual_expire, background, remark, mobile, wechat, label, city';
        $user = $userModel->findOne(['user_id' => $userId], $field);
        if(empty($user)) {
            return errorResult();
        }
        
        //$user['mobile'] = empty($user['mobile']) ? 0 : 1;

        if($params['signature'] !== sha1($params['rawData'] . $user['session_key'])){ //验证不通过
            return errorResult('b');
        }
        
        
        $pc = new \app\client\lib\WXBizDataCrypt\WXBizDataCrypt($appId, $user['session_key']);
        
        $errCode = $pc->decryptData($params['encryptedData'], $params['iv'], $userInfo);
        
        if($errCode == 0) {
            $userInfo = json_decode($userInfo, true);
            $updateData = [];
            
            if(!empty($userInfo['city'])) {
                $city = model('Area')->findOne(['pinyin' => strtolower($userInfo['city'])], ['name']);
                if(!empty($city) && $city['name'] != $user['city']) {
                    $user['city'] = $updateData['city'] = $city['name'];
                }
            }
            
            
            if($user['nickname'] !== $userInfo['nickName']){
                $updateData['nickname'] = $userInfo['nickName'];
            }
            
            if($user['avatar'] !== $userInfo['avatarUrl']){
                $updateData['avatar'] = $userInfo['avatarUrl'];
            }
            
            if($user['sex'] !== $userInfo['gender']){
                $updateData['sex'] = $userInfo['gender'];
            }
            
            if(empty($user['unionid']) && !empty($userInfo['unionId'])){ //还没有保存unionid
                $updateData['unionid'] = $userInfo['unionId'];
            }
            
            if(!empty($updateData)) {
                $user = array_merge($user, $updateData);
                $userModel->modify(['user_id' => $userId], $updateData);
            }
            
            unset($user['unionid']);
            unset($user['session_key']);
            
            $chatModel = model('Chat');
            Task::async(function() use($userId, $user, &$chatModel) {
                $user['user_id'] = $userId;
                $user['chat_number'] = $chatModel->where(['user_id' => $userId])->count();
                $user['goods_number'] = $chatModel->where(['user_id' => $userId, 'chat_type' => 2])->count();
                
                $redis = new Redis();
                $redis->set('user_' . $userId, $user);
                $redis->close();
                
                return true;
            });
            
            $user['isAuth'] = $user['avatar'] === '';
                
            return successResult($user);
            
        }else{
            return errorResult('c');
        }
    }
    
    
    public function update() {
        $params = request()->post();
        if(empty($params)){
            return errorResult();
        }
        
        $keys = array_keys($params);
        $field = $keys[0];
        $value = $params[$field];
        unset($keys);
        
        $userId = $this->userid;
        $rs = model('User')->modify(['user_id' => $userId], $params);
        if(!$rs) {
            return errorResult();
        }
        
        Task::async(function() use($userId, $field, $value){
            $key = 'user_' . $userId;
            try {
                $redis = new Redis();
                $user = $redis->get($key);
                if(!empty($user)) {
                    $user = json_decode($user, true);
                    $user[$field] = $value;
                    
                    $redis->set($key, $user);
                }
                $redis->close();
            } catch (\Exception $e) {
            }
            
            return true;
        });
        
        return successResult();
    }
    
    public function getUserItem() {
        $field = request()->route('field', '', 'trim');
        if($field === '') {
            return errorResult();
        }
        
        try {
            $value = model('User')->where(['user_id' => $this->userid])->value($field);
        } catch (\Exception $e) {
        }
        
        return successResult(['user_type' => $value]);
        
    }
    
    public function getUserByUserId() {
        $userId = request()->route('userId', 0, 'intval');
        if($userId <= 0) {
            return errorResult();
        }
        
        $redis = new Redis();
        $user = $redis->get(redisUserKey($userId));
        $redis->close();
        
        return successResult(['user' => $user]);
    }
    
    public function number() {
        $userId = $this->userid;
        
        $redis = new Redis();
        $praiseNumber = $redis->get(redisUserChatPraiseKey($userId));
        $redis->close();
        $fansNumber = model('FollowUser')->where(['user_id' => $this->userid])->count();
        $chatNumber = model('Chat')->where(['user_id' => $userId])->count();
        
        return successResult(['praise' => $praiseNumber, 'chat' => $chatNumber, 'fans' => $fansNumber]);
    }
    
    public function fansNumber() {
        $number = model('FollowUser')->where(['user_id' => $this->userid])->count();
        return successResult(['number' => $number]);
    }
    
}








